<template>
    <div class="work-modal" v-if="visible">
        <input
            ref="uploadFile"
            type="file"
            style="display: none;"
            multiple="multiple"
            @change="fileChange"
        />
        <modal
            :visible.sync="visible"
            title='新建工单'
            width="640px"
            @confirm="confirm"
        >
            <div slot="body" class="work-modal-body">
                <div class="line"></div>
                <el-form
                    ref="ruleForm"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="100px"
                    class="work-modal-form"
                >
                    <el-form-item label="问题描述：" prop="desc">
                        <div class="work-modal-desc">
                            <el-input
                                class="work-modal-input"
                                v-model="ruleForm.desc"
                                type="textarea"
                                resize="none"
                                maxlength="200"
                            >
                            </el-input>
                            <div class="work-modal-num">
                                <span>{{ruleForm.desc.length}}</span>/200
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="上传附件：" prop="stFileUrls">
                        <div class="work-modal-upload">
                            <div class="upload-btn" @click="$refs.uploadFile.click();">
                                <i class="icon-add">+</i>
                                <p>选择文件</p>
                            </div>
                            <div class="upload-tips">未选择任何文件</div>
                        </div>
                        <div class="upload-files">
                            <el-scrollbar style="height: 100%;">
                                <div
                                    class="file-item"
                                    v-for="(file, index) in ruleForm.stFileUrls"
                                    :key="index"
                                >
                                    <div class="file-info">
                                        <p class="file-name">{{file.name}}</p>
                                        <i class="icon-file-close" @click="fileDel(file)"></i>
                                    </div>
                                    <div class="progress-outer">
                                        <div
                                            class="progress-inner"
                                            :style="{width: `${file.percentage * 100}%`}"
                                        ></div>
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </modal>
    </div>
</template>
<script>
import modal from 'components/modal/index.vue'; // 弹框组件（可以用你自己的改改样式）
import { platform } from 'config/up366config.js'; // 上传区分环境 demo || test || ''
import { clientTicket } from 'javascript/api/zhujiaoApi'; // 上传工单接口
import { sendTextMsg } from '../../im-utils/webIm'; // 上传成功发环信消息（你那可能用不到）

export default {
    data() {
        return {
            // 弹框出现
            visible: false,
            // 表单数据
            ruleForm: {
                desc: '',
                stFileUrls: [],
            },
            // 表单校验
            rules: {
                desc: [
                    { required: true, message: '请输入问题描述', trigger: 'blur' },
                ],
            },
            // 阿里云上传
            uploaderObj: '',
            // 需要上传阿里云文件的数量
            needUploadNum: 0,
            // 已经上传阿里云文件的数量
            alreadyUploadNum: 0,
            // 用户选择本地的文件
            userAddFile: [],
            // 阿里云添加的文件
            aliAddFile: [],
            // 已经上传过的文件记录
            fileRecord: [],
            // 学生uid
            uid: 0,
            // 学生班级id
            courseId: 0,
            // 群id
            groupId: '',
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        /**
         * 实例阿里云上传
         */
        init() {
            this.uploaderObj = new up366AliUploader({
                platForm: platform,
            });
            this.uploaderObj.init();

            const _this = this;
            this.uploaderObj.uploader.on('fileQueued', (file) => {
                _this.aliAddFile.push(file);
            });
            this.uploaderObj.uploader.on('uploadProgress', (file, percentage) => {
                for (let i = 0; i < this.ruleForm.stFileUrls.length; i++) {
                    if (this.ruleForm.stFileUrls[i].name === file.name) {
                        this.ruleForm.stFileUrls[i].percentage = percentage;
                        break;
                    }
                }
            });
            this.uploaderObj.uploader.on('uploadSuccess', () => {
            // 上传完成
                _this.complete();
            });
            this.uploaderObj.uploader.on('uploadError', () => {
                _this.needUploadNum--;
                // 所有上传阿里云的文件都失败了
                if (_this.needUploadNum === 0) {
                    console.log('文件上传失败');
                }
                _this.$refs.uploadFile.value = null;
            });
        },

        /**
         * 打开弹窗
         */
        openModal(options) {
            this.visible = true;
            this.uid = options.uid;
            this.courseId = options.courseId;
            this.groupId = options.groupId;

            this.needUploadNum = 0;
            this.alreadyUploadNum = 0;
            this.userAddFile = [];
            this.aliAddFile = [];
            this.fileRecord = [];
            this.ruleForm.desc = '';
            this.ruleForm.stFileUrls = [];
        },

        /**
         * 确认
         */
        confirm() {
            if (this.ruleForm.desc === '' || this.ruleForm.stFileUrls.length === 0) return;

            // 创建工单接口
            // clientTicket({
            //     uid: this.uid,
            //     classId: this.courseId,
            //     stFileUrls: JSON.stringify(this.ruleForm.stFileUrls),
            //     desc: this.ruleForm.desc,
            // })
            //     .then((res) => {
            //         if (res.result.code === 0) {
            //         // 发一条上传日志的消息
            //             sendTextMsg({ groupId: this.groupId, msgText: '同学，你的问题老师正在处理，为了方便找到出现问题的原因，请点击上传日志，上传过程中请勿离开。', ext: { needUploadLog: true } });

            //             // 关闭弹框
            //             this.visible = false;
            //         }
            //     });
        },

        /**
         * 选择文件
         */
        fileChange(event) {
            const Event = event;
            if (Event.target) {
                const fileList = Event.target.files;

                // 用户选择的文件
                this.userAddFile = [];
                for (let i = 0; i < fileList.length; i++) {
                    this.userAddFile.push(fileList[i]);
                }

                // 重置input值
                Event.target.value = '';

                // 重置此次阿里云上传的文件
                this.aliAddFile = [];

                // 开始上传
                this.upload();
            }
        },

        /**
         * 上传文件
         */
        upload() {
            if (this.userAddFile.length === 0) return;
            this.needUploadNum = 0;
            this.alreadyUploadNum = 0;

            for (let i = 0; i < this.userAddFile.length; i++) {
                const index = this.fileRecord.findIndex((item) => item.name === this.userAddFile[i].name);
                if (index > -1) {
                    this.ruleForm.stFileUrls.push({
                        url: this.fileRecord[index].url,
                        name: this.fileRecord[index].name,
                        percentage: 1,
                    });
                } else {
                    this.needUploadNum++;
                    this.uploaderObj.uploader.addFiles(this.userAddFile[i]);
                }
            }

            this.uploaderObj.uploader.upload();
        },

        /**
         * 上传完成
         */
        complete() {
            // 需要上传文件
            this.alreadyUploadNum++;
            if (this.alreadyUploadNum !== this.needUploadNum) return;

            for (let i = 0; i < this.aliAddFile.length; i++) {
                if (this.aliAddFile[i].fileObjectInfo && this.aliAddFile[i].fileObjectInfo.previewUrl) {
                    this.fileRecord.push({
                        name: this.aliAddFile[i].name,
                        url: this.aliAddFile[i].fileObjectInfo.previewUrl,
                    });
                    this.ruleForm.stFileUrls.push({
                        name: this.aliAddFile[i].name,
                        url: this.aliAddFile[i].fileObjectInfo.previewUrl,
                        percentage: 1,
                    });
                }
            }
        },

        /**
         * 删除文件
         */
        fileDel(file) {
            const index = this.ruleForm.stFileUrls.findIndex((item) => item.name === file.name);
            if (index > -1) {
                this.ruleForm.stFileUrls.splice(index, 1);
            }
        },
    },
};
</script>
<style lang="scss">
.work-modal {
    .el-textarea {
        color: #333;
        font-size: 14px;
        height: 70px;

        .el-textarea__inner {
            height: 70px;
            color: #333;
            font-size: 14px;
            padding: 0;
            border: none;
            background: #F7F9FF;
        }
    }

    .el-form-item {
        margin-bottom: 15px;
    }

    .upload-files {
        .el-scrollbar__wrap {
            overflow-x: hidden;
            max-height: 200px;
            box-sizing: border-box;
        }
    }
}
</style>
<style lang="scss" scoped>
.work-modal {
    .icon-file-close {
        @include im-icon-operate(10px, 10px, './images/modal-close', true);
    }

    .work-modal-body {
        padding: 0 20px;

        .line {
            width: 100%;
            height: 1px;
            background: #F2F2F3;
            margin: 14px 0 32px 0;
        }

        .work-modal-form {
            padding: 0 0 20px 46px;
        }

        .work-modal-desc {
            width: 410px;
            height: 108px;
            background: #F7F9FF;
            border-radius: 4px;
            border: 1px solid #E8E8E8;
            box-sizing: border-box;
            padding: 10px;

            .work-modal-num {
                color: #999;
                font-size: 12px;
                text-align: right;
                line-height: normal;

                & span {
                    color: #6C92FF;
                }
            }
        }

        .work-modal-upload {
            display: flex;
            align-items: center;

            .upload-btn {
                width: 97px;
                height: 40px;
                background: #F7F9FF;
                border-radius: 4px;
                border: 1px solid #E8E8E8;
                color: #6C92FF;
                display: flex;
                align-items: center;
                justify-content: center;

                .icon-add {
                    margin-right: 8px;
                    font-style: normal;
                }

                & p {
                    font-size: 14px;
                }
            }

            .upload-tips {
                color: #999;
                font-size: 14px;
                margin-left: 10px;
            }
        }

        .file-item {
            .file-info {
                width: 110px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 10px 0 5px;

                .file-name {
                    width: 60px;
                    margin-right: 13px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
            }

            .progress-outer {
                width: 110px;
                height: 2px;
                background: #D8D8D8;
                border-radius: 1px;

                .progress-inner {
                    height: 2px;
                    background: #6C92FF;
                    border-radius: 1px;
                }
            }
        }
    }
}
</style>
